import { onBeforeMount, onBeforeUnmount } from 'vue';
import { getCar } from '../utils/three_home'

let ws: WebSocket

export function createWS() {

        onBeforeMount(() => {

                init()

        })
        onBeforeUnmount(() => {

                ws.removeEventListener('message', handleMessage)

        })

}

function init() {

        ws = new WebSocket('ws://127.0.0.1:5555')

        ws.addEventListener('open', handleOpen, false)
        ws.addEventListener('close', handleClose, false)
        ws.addEventListener('error', handleError, false)
        ws.addEventListener('message', handleMessage, false)
        return ws
}

function handleOpen(e: Event) {
        console.log('websocket open');
}

function handleClose(e: Event) {
        console.log(e);
}

function handleError(e: Event) {
        console.log(e);
}

function handleMessage(e: MessageEvent) {

        let data = JSON.parse(e.data)

        getCar(data)

}

